# -*-coding: Utf-8 -*-
# @File : House .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2023/10/11

from flask import Blueprint, request, render_template, session, redirect, jsonify

house_view = Blueprint('house', __name__, url_prefix='/house', template_folder='templates')


@house_view.route('/update_data', methods=['GET'])
def update_data():
    data = request.args
    condition = data.get('db')
    if condition == '1':
        request.spider.save_to_csv()
    elif condition == '2':
        request.spider.save_to_mysql()
    elif condition == '3':
        request.spider.save_to_all()
    else:
        return '必须携带存储库'
    return 'ok'


@house_view.route('/house_data', methods=["GET"])
def get_house_data():
    # house_name
    condition = request.args.get('condition')
    if not condition:
        sql = 'select * from house_info'
        house_data = request.mysql_handler.query(sql, one=False)
    if condition == 'house_name':
        sql = 'select * from house_info order by house_name'
        house_data = request.mysql_handler.query(sql, one=False)
        return jsonify({'code': 200, 'data': house_data})
    return render_template('index.html', house_data=house_data)


@house_view.route('/edit/del', methods=["GET"])
def del_house_data():
    data = request.args
    house_id = data.get('house_id')
    if not house_id:
        return jsonify({'code': 201, 'message': '房源数据ID'})
    res = request.mysql_handler.exec(f'select house_name from house_info where id = {house_id};')
    if not res:
        return jsonify({'code': 201, 'message': '房源数据不存在'})
    sql = f'delete  from house_info where id = {house_id};'
    request.mysql_handler.exec(sql)
    return jsonify({'code': 200, 'message': '房源数据删除成功'})
